/** 
 * @CopyRight (c) 2012-2012
 * @Company <江苏瑞德信息技术有限公司>
 * @Project <eshop>
 * @JDK_Version_Used:<JDK1.6>
 * @Description:TODO<描述用途>
 * @Title: AddWeb.java
 * @Author: <何俊>
 * @Author_of_Contact <E:azj1001@sina.com T:18651831939>
 * @Date 2012-11-13 下午3:35:51
 * @Modified_By: <修改人>
 * @Modified_of_Contact <修改人联系方式>
 * @Modified_Date <修改日期时间>
 * @Why & What is modified <修改原因描述>
 * @Version v1.00
 */
package com.e.buy.web.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.commons.dbclient.Batchs;
import cn.commons.exception.proxy.AzjSqlExceptionProxy;
import cn.commons.query.ConditionBean;

import com.e.buy.BuyTools;
import com.e.buy.bean.back.manager.CmiAdminUser;
import com.e.buy.bean.back.manager.cmi_ad.CmiAd;
import com.e.buy.bean.back.manager.cmi_ad.CmiAdLocation;
import com.e.buy.bean.back.manager.cmi_ad.CmiAdType;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoods;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsBrand;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsCategroy;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsProperties;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsVariety;
import com.e.buy.bean.back.manager.cmi_news.CmiNews;
import com.e.buy.bean.back.manager.cmi_news.CmiNewsType;
import com.e.buy.bean.back.manager.cmi_power.CmiRole;
import com.e.buy.bean.back.manager.cmi_sigle.CmiSingle;
import com.e.buy.bean.back.manager.cmi_sigle.CmiSingleType;
import com.e.buy.enums.Commons;
import com.e.buy.enums.Status;
import com.e.buy.service.CommonsServiceClient;

/**
 * @Description:TODO(描述类别作用)
 * @author <何俊>
 * @date 2012-11-13 下午3:35:51
 * @version v1.0
 * @Other :@see #Files
 */
@Controller
@RequestMapping("/impl_add")
public class AdminAddWeb extends BuyTools {

	@Resource
	private CommonsServiceClient commons = null;

	public void setCommons(CommonsServiceClient commons) {
		this.commons = commons;
	}

	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/backAdd.adm")
	public String commonsAdd(HttpSession session, @RequestParam("dt") String datas, @RequestParam("st") String st) {
		String msg = "";
		int errorCode = 0;
		String sql = null;
		String doWhatMsg = "";
		boolean hasDone = false;
		List<Batchs> batchs = null;
		List<Object[]> batchArgs = null;
		Object[] args = new Object[0];
		JSONObject success = new JSONObject();
		Commons.BackProcess e = Commons.BackProcess.DEFAULT;
		List<ConditionBean> beans = new ArrayList<ConditionBean>();
		CmiAdminUser user = ((CmiAdminUser) session.getAttribute("loginAdmin")).clone();

		try {
			e = Commons.getBackProcess(st);
			sql = commons.getEnumSql(e, Status.ADD);
			msg = this.getWebProperties("web", "msg.success");
			doWhatMsg = this.getWebProperties("web", e.getStatus() + ".ADD.log");
			switch (e) {
			case ADMIN_POWER_CMI_ROLE:
				// 参数
				hasDone = true;
				CmiRole role = (CmiRole) toolsbox.jsonstr2Object(datas, CmiRole.class);
				batchs = new ArrayList<Batchs>();
				batchArgs = new ArrayList<Object[]>();
				doWhatMsg = doWhatMsg + "[" + role.getRoleName() + "]";

				// 写入角色信息
				batchArgs.add(new Object[] { role.getRoleName(), role.getRoleDesc() });
				batchs.add(new Batchs(commons.getEnumSql(e, Status.ADD), batchArgs));

				// 分配角色权限
				batchArgs = new ArrayList<Object[]>();
				beans.add(new ConditionBean("s.uuid", "customer", "s.uuid IN (" + role.getRolePower() + ")", "0", null));
				batchArgs.add(service.unionConditionBeanArgs(beans, role.getRoleName()));
				sql = commons.getEnumSql(Commons.BackProcess.ADMIN_POWER_CMI_ROLE_POWER, Status.ADD);
				batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));

				// 执行
				service.executeBatchSQL(batchs);
				break;
			case ADMIN_INFO:
				// 参数
				hasDone = true;
				CmiAdminUser admin = (CmiAdminUser) toolsbox.jsonstr2Object(datas, CmiAdminUser.class);
				batchs = new ArrayList<Batchs>();
				batchArgs = new ArrayList<Object[]>();
				doWhatMsg = doWhatMsg + "[" + admin.getAid() + "]";

				// 写入管理员信息
				batchArgs.add(new Object[] { admin.getAid(), admin.getAmail(), admin.getApass(), admin.getRoleId() });
				batchs.add(new Batchs(commons.getEnumSql(e, Status.ADD), batchArgs));

				// 分配管理员的权限为指定的角色权限
				if (admin.getRoleId() > 0) {
					batchArgs = new ArrayList<Object[]>();
					beans = new ArrayList<ConditionBean>();
					beans.add(new ConditionBean("uuid", "customer",
							"EXISTS(SELECT 1 FROM cmi_role_power p WHERE p.roleid = " + admin.getRoleId()
									+ " AND p.sysid = s.uuid)", "0", null));
					batchArgs.add(service.unionConditionBeanArgs(beans, admin.getAid()));
					sql = commons.getEnumSql(Commons.BackProcess.ADMIN_INFO_POWER, Status.ADD);
					batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));
				}

				// 执行
				service.executeBatchSQL(batchs);

				success.element("saveRecord", datas);
				break;
			case GOODS_CATEGROY:
				CmiGoodsCategroy c = (CmiGoodsCategroy) toolsbox.jsonstr2Object(datas, CmiGoodsCategroy.class);
				args = new Object[] { c.getCategroy(), c.getGroups() };
				doWhatMsg = doWhatMsg + "[" + c.getCategroy() + "]";
				break;
			case GOODS_CATEGROY_PROPERTIES:
				CmiGoodsProperties p = (CmiGoodsProperties) toolsbox.jsonstr2Object(datas, CmiGoodsProperties.class);
				args = new Object[] { p.getProName(), p.getCategroyId(), p.getGroups(), p.getSearchAble(),
						p.getRelationAble(), p.getChoseAble(), p.getInputs(), p.getValueList(), p.getPsort() };
				doWhatMsg = doWhatMsg + "[类型:" + p.getCategroyId() + " 属性:" + p.getProName() + "]";
				break;
			case GOODS_BRAND:
				CmiGoodsBrand b = (CmiGoodsBrand) toolsbox.jsonstr2Object(datas, CmiGoodsBrand.class);
				args = new Object[] { b.getBrandName(), b.getBrandNet(), b.getBrandLogo(), b.getBrandDesc(),
						b.getBrandSort(), b.getBrandShow() };
				doWhatMsg = doWhatMsg + "[" + b.getBrandName() + "]";
				break;
			case GOODS_VARIETY:
				CmiGoodsVariety v = (CmiGoodsVariety) toolsbox.jsonstr2Object(datas, CmiGoodsVariety.class);
				args = new Object[] { v.getVarName(), v.getVarUp(), v.getVarUnit(), v.getVarSort(), v.getVarShow(),
						v.getVarNav(), v.getVarHome(), v.getVarProp(), v.getVarPrice(), v.getVarCss(),
						v.getVarKeyword(), v.getVarDesc() };
				doWhatMsg = doWhatMsg + "[" + v.getVarName() + "]";
				break;
			case NEWS_TYPE:
				CmiNewsType n = (CmiNewsType) toolsbox.jsonstr2Object(datas, CmiNewsType.class);
				args = new Object[] { n.getName(), n.getIdx()};
				doWhatMsg = doWhatMsg + "[" + n.getName() + "]";
				break;
			case SINGLE_TYPE:
				CmiSingleType s = (CmiSingleType) toolsbox.jsonstr2Object(datas, CmiSingleType.class);
				args = new Object[] { s.getName(), s.getIdx()};
				doWhatMsg = doWhatMsg + "[" + s.getName() + "]";
				break;
			case AD_TYPE:
				CmiAdType at = (CmiAdType) toolsbox.jsonstr2Object(datas, CmiAdType.class);
				args = new Object[] { at.getName(), at.getTypeDesc()};
				doWhatMsg = doWhatMsg + "[" + at.getName() + "]";
				break;
			case AD_LOC:
				CmiAdLocation al = (CmiAdLocation) toolsbox.jsonstr2Object(datas, CmiAdLocation.class);
				args = new Object[] { al.getName(), al.getWidth(),al.getHeight(),al.getLocDesc()};
				doWhatMsg = doWhatMsg + "[" + al.getName() + "]";
				break;
			default:
				errorCode = 99;
				msg = this.getWebProperties("web", "msg.fail.undefiend.status");
				break;
			}
			if (!hasDone) {
				service.executeSQL(sql, args);
			}
			try {
				commons.noteAdminLog(doWhatMsg, user.getUuid());
			} catch (Exception ex) {
			}

		} catch (Exception ex) {
			log4j.error("ADD Datas Exception:" + ex);
			try {
				AzjSqlExceptionProxy p = new AzjSqlExceptionProxy(ex);
				errorCode = p.getErrorCode();
				// 唯一键存在重复项
				if (errorCode == 1062) {
					msg = this.getWebProperties("web", e.getStatus() + ".1062");
				} else {
					msg = this.getWebProperties("web", "msg.fail");
				}
			} catch (Exception e2) {
				errorCode = 100;
				msg = this.getWebProperties("web", "msg.fail");
			}
		}
		success.element("error", errorCode);
		success.element("msg", msg);
		return success.toString();
	}

	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/backFileUploadAdd.adm")
	public String commonsFileUploadAdd(HttpServletRequest req, HttpSession session,
			@RequestParam("file") MultipartFile[] file, @RequestParam("dt") String datas, @RequestParam("st") String st) {
		String msg = "";
		int errorCode = 0;
		String sql = null;
		String doWhatMsg = "";
		boolean hasDone = false;
		// List<Batchs> batchs = null;
		// List<Object[]> batchArgs = null;
		Object[] args = new Object[0];
		JSONObject success = new JSONObject();
		Commons.BackProcess e = Commons.BackProcess.DEFAULT;
		// List<ConditionBean> beans = new ArrayList<ConditionBean>();
		CmiAdminUser user = ((CmiAdminUser) session.getAttribute("loginAdmin")).clone();

		try {
			e = Commons.getBackProcess(st);
			sql = commons.getEnumSql(e, Status.ADD);
			msg = this.getWebProperties("web", "msg.success");
			doWhatMsg = this.getWebProperties("web", e.getStatus() + ".ADD.log");
			switch (e) {
			case GOODS_BRAND:
				CmiGoodsBrand b = (CmiGoodsBrand) toolsbox.jsonstr2Object(datas, CmiGoodsBrand.class);
				MultipartFile f = file[0];
				String savePath = "/data/brandlogo/" + toolsbox.getJavaUUID();
				boolean save = true;
				long brandlogoSize = f.getSize();
				String brandlogoName = f.getOriginalFilename();
				String webapp = req.getSession().getServletContext().getRealPath("/");
				if (brandlogoSize == 0 && StringUtils.isEmpty(brandlogoName)) {
					b.setBrandLogo(null);
				} else {
					// 获取请求的本地路径
					String sufix = brandlogoName.substring(brandlogoName.lastIndexOf("."));
					savePath = savePath + sufix;
					save = this.writUploadPic(f.getInputStream(), webapp + savePath);
					b.setBrandLogo(savePath);
				}
				if (save) {
					log4j.debug("Add--save upload file in [" + webapp + savePath + "]");
					args = new Object[] { b.getBrandName(), b.getBrandNet(), b.getBrandLogo(), b.getBrandDesc(),
							b.getBrandSort(), b.getBrandShow() };
					doWhatMsg = doWhatMsg + "[" + b.getBrandName() + "]";
				}
				break;
			case NEWS:
				CmiNews news = (CmiNews) toolsbox.jsonstr2Object(datas, CmiNews.class);
				MultipartFile newsF = file[0];
				String newsSavePath = "/data/news/" + toolsbox.getJavaUUID();
			    boolean newsSave = true;
				long newsImgSize = newsF.getSize();
				String newsImgName = newsF.getOriginalFilename();
				webapp = req.getSession().getServletContext().getRealPath("/");
				if (newsImgSize == 0 && StringUtils.isEmpty(newsImgName)) {
					news.setNewsImg(null);
				} else {
					// 获取请求的本地路径
					String sufix = newsImgName.substring(newsImgName.lastIndexOf("."));
					newsSavePath = newsSavePath + sufix;
					newsSave = this.writUploadPic(newsF.getInputStream(), webapp + newsSavePath);
					news.setNewsImg(newsSavePath);
				}
				if (newsSave) {
					log4j.debug("Add--save upload file in [" + webapp + newsSavePath + "]");
					args = new Object[] { news.getNewsTitle(), news.getTypeId(), news.getNewsSrc(), news.getNewsImg(), news.getCreateTime(),
							news.getNewsRec(), news.getSummary(),news.getContent(),news.getOrderNum() };
					doWhatMsg = doWhatMsg + "[" + news.getNewsTitle() + "]";
				}
				break;
			case SINGLE:
				CmiSingle single = (CmiSingle) toolsbox.jsonstr2Object(datas, CmiSingle.class);
				MultipartFile singleF = file[0];
				String singleSavePath = "/data/sigle/" + toolsbox.getJavaUUID();
			    boolean singleSave = true;
				long singleImgSize = singleF.getSize();
				String singleImgName = singleF.getOriginalFilename();
				webapp = req.getSession().getServletContext().getRealPath("/");
				if (singleImgSize == 0 && StringUtils.isEmpty(singleImgName)) {
					single.setImg(null);
				} else {
					// 获取请求的本地路径
					String sufix =singleImgName.substring(singleImgName.lastIndexOf("."));
					singleSavePath = singleSavePath + sufix;
					singleSave = this.writUploadPic(singleF.getInputStream(), webapp + singleSavePath);
					single.setImg(singleSavePath);
				}
				if (singleSave) {
					log4j.debug("Add--save upload file in [" + webapp +singleSavePath + "]");
					args = new Object[] { single.getName(), single.getTypeId(), single.getImg(), single.getContent(),
							single.getIsRec(), single.getIdx()};
					doWhatMsg = doWhatMsg + "[" + single.getName() + "]";
				}
				break;
			case AD:
				CmiAd ad = (CmiAd) toolsbox.jsonstr2Object(datas, CmiAd.class);
				MultipartFile adF = file[0];
				String adSavePath = "/data/ad/" + toolsbox.getJavaUUID();
			    boolean adSave = true;
				long adImgSize = adF.getSize();
				String adImgName = adF.getOriginalFilename();
				webapp = req.getSession().getServletContext().getRealPath("/");
				if (adImgSize == 0 && StringUtils.isEmpty(adImgName)) {
					ad.setAdImg(null);
				} else {
					// 获取请求的本地路径
					String sufix =adImgName.substring(adImgName.lastIndexOf("."));
					adSavePath = adSavePath + sufix;
					adSave = this.writUploadPic(adF.getInputStream(), webapp + adSavePath);
					ad.setAdImg(adSavePath);
				}
				if (adSave) {
					log4j.debug("Add--save upload file in [" + webapp +adSavePath + "]");
					args = new Object[] { ad.getName(), ad.getAdType(), ad.getAdLocId(), ad.getStartTime(),
							ad.getEndTime(), ad.getLink(),ad.getAdImg(),ad.getImgLink(),ad.getContractUser(),ad.getContractEmail(),ad.getContractPhone(),ad.getEnable()};
					doWhatMsg = doWhatMsg + "[" + ad.getName() + "]";
				}
				break;
				
			default:
				errorCode = 99;
				msg = this.getWebProperties("web", "msg.fail.undefiend.status");
				break;
			}
			if (!hasDone) {
				service.executeSQL(sql, args);
			}
			try {
				commons.noteAdminLog(doWhatMsg, user.getUuid());
			} catch (Exception ex) {
			}

		} catch (Exception ex) {
			log4j.error("ADD Datas Exception:" + ex);
			try {
				AzjSqlExceptionProxy p = new AzjSqlExceptionProxy(ex);
				errorCode = p.getErrorCode();
				// 唯一键存在重复项
				if (errorCode == 1062) {
					msg = this.getWebProperties("web", e.getStatus() + ".1062");
				} else {
					msg = this.getWebProperties("web", "msg.fail");
				}
			} catch (Exception e2) {
				errorCode = 100;
				msg = this.getWebProperties("web", "msg.fail");
			}
		}
		success.element("error", errorCode);
		success.element("msg", msg);
		return success.toString();
	}

	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/goodsAdd.adm")
	public String goodsAdd(HttpServletRequest req, HttpSession session, @RequestParam("dt") String datas,
			@RequestParam("st") String st, @RequestParam("goodsImage_b") MultipartFile file1,
			@RequestParam("goodsImage_s") MultipartFile file2) {
		String msg = "";
		int errorCode = 0;
		String sql = null;
		String doWhatMsg = "";
		Object[] args = new Object[0];
		JSONObject success = new JSONObject();
		Commons.BackProcess e = Commons.BackProcess.DEFAULT;
		CmiAdminUser user = ((CmiAdminUser) session.getAttribute("loginAdmin")).clone();

		try {
			e = Commons.getBackProcess(st);
			sql = commons.getEnumSql(e, Status.ADD);
			msg = this.getWebProperties("web", "msg.success");
			doWhatMsg = this.getWebProperties("web", e.getStatus() + ".ADD.log");
			// 获取参数对象
			CmiGoods g = (CmiGoods) toolsbox.jsonstr2Object(datas, CmiGoods.class);

			// 商品图片上传
			String savePath = "/data/goods/" + toolsbox.getJavaUUID();
			savePath = saveGoodsImage(file1, savePath, req);
			if (savePath == null && !this.isEmptyStr(g.getGoodsImage_b_url())) {
				savePath = g.getGoodsImage_b_url();
			}
			g.setGoodsImage_b(savePath);
			System.out.println(savePath);
			// 商品缩略图
			savePath = "/data/goods/" + toolsbox.getJavaUUID();
			savePath = saveGoodsImage(file2, savePath, req);
			if (savePath == null && !this.isEmptyStr(g.getGoodsImage_s_url())) {
				savePath = g.getGoodsImage_s_url();
			}
			g.setGoodsImage_s(savePath);

			// 设置商品货号
			if (this.isEmptyStr(g.getGoodsBill())) {
				g.setGoodsBill(null);
			}
			args = new Object[] { g.getGoodsName(), g.getGoodsNameColor(), g.getGoodsNameFont(), g.getGoodsBill(),
					g.getGoodsBill(), g.getVarietyId(), g.getExtendVarietyId(), g.getBrandId(), g.getSalePrice(),
					g.getMemberPrice(), g.getGoodsRate(), g.getMarketPrice(), g.getSaleScore(), g.getLevelScore(),
					g.getScoreBy(), g.getRate(), g.getRateStart(), g.getRateEnd(), g.getGoodsImage_b(),
					g.getGoodsImage_s(), g.getDetail(), g.getGoodsWeight(), g.getGoodsWeightUnit(), g.getGoodsSum(),
					g.getGoodsWaring(), g.getGoodsBetter(), g.getGoodsNew(), g.getGoodsHot(), g.getGoodsDm8(),
					g.getGoodsDm1(), g.getGoodsFreeSend(), g.getGoodsKey(), g.getGoodsDesc(), g.getFactoryRemark(),
					g.getCategroyId(), g.getFieldsList(), g.getJoinGoods(), g.getParts(), g.getJoinArtice() };
			doWhatMsg = doWhatMsg + "[" + g.getGoodsName() + "]";
			service.executeSQL(sql, args);
			try {
				commons.noteAdminLog(doWhatMsg, user.getUuid());
			} catch (Exception ex) {
			}

		} catch (Exception ex) {
			log4j.error("ADD Datas Exception:" + ex);
			try {
				AzjSqlExceptionProxy p = new AzjSqlExceptionProxy(ex);
				errorCode = p.getErrorCode();
				// 唯一键存在重复项
				if (errorCode == 1062) {
					msg = this.getWebProperties("web", e.getStatus() + ".1062");
				} else {
					msg = this.getWebProperties("web", "msg.fail");
				}
			} catch (Exception e2) {
				errorCode = 100;
				msg = this.getWebProperties("web", "msg.fail");
			}
		}
		success.element("error", errorCode);
		success.element("msg", msg);
		return success.toString();
	}

	/**
	 * @throws IOException
	 * @Description:<存储单张图片,返回存放的图片网络路径地址>
	 * @title: saveGoodsImage
	 * @param f
	 * @param req
	 * @return String 返回类型
	 * @throws
	 */
	private String saveGoodsImage(MultipartFile f, String savePath, HttpServletRequest req) throws IOException {
		String retPath = null;
		long brandlogoSize = f.getSize();
		String brandlogoName = f.getOriginalFilename();
		String webapp = req.getSession().getServletContext().getRealPath("/");
		if (brandlogoSize == 0 && StringUtils.isEmpty(brandlogoName)) {
			retPath = null;
		} else {
			// 获取请求的本地路径
			String sufix = brandlogoName.substring(brandlogoName.lastIndexOf("."));
			savePath = savePath + sufix;
			if (this.writUploadPic(f.getInputStream(), webapp + savePath)) {
				retPath = savePath;
			} else {
				retPath = null;
			}
		}
		return retPath;
	}
}
